package com.gitee.cirnochat.common.aop;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.UUID;

/**
 * 请求响应日志 AOP
 *
 * @author FlanChan
 **/


@Aspect
@Component
@ConditionalOnClass(HttpServletRequest.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.ANY)
@Slf4j
@RequiredArgsConstructor
public class LogInterceptor {

    private final HttpServletRequest httpServletRequest;

    private static final long MAX_COST_TIME = 60_000L; // 最大耗时 60 秒


    @Around("@annotation(org.springframework.messaging.handler.annotation.MessageMapping)")
    public Object doWebSocketLogInterceptor(ProceedingJoinPoint point) throws Throwable {
// 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        // 获取方法名
        String methodName = point.getSignature().toShortString();
        // 获取参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        log.info("WebSocket request start, id: {}, method: {}, params: {}", requestId, methodName, reqParam);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = point.proceed();
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("WebSocket request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
        if (totalTimeMillis > MAX_COST_TIME) {
            log.warn("WebSocket request id: {} cost more than 1 minute: {}ms", requestId, totalTimeMillis);
        }
        log.info("WebSocket response, id: {}, result: {}", requestId, result);
        return result;
    }


    /**
     * 执行拦截
     */
    @Around("execution(* com.gitee.cirnochat..controller..*(..)) && !@annotation(org.springframework.messaging.handler.annotation.MessageMapping)")
    public Object doHttpLogInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String url = httpServletRequest.getRequestURI();

        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("Http request start，id: {}, path: {}, ip: {}, params: {}", requestId, url,
                httpServletRequest.getRemoteHost(), reqParam);
        // 执行原方法
        Object result = point.proceed();
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("Http request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
        if (totalTimeMillis > MAX_COST_TIME) {
            log.warn("Http request id: {} cost more than 1 minute: {}ms", requestId, totalTimeMillis);
        }
        log.info("Http response, id: {}, result: {}", requestId, result);
        return result;
    }
}

